package com.wcj.tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class 二叉树的后序遍历 {



    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null){
            return new ArrayList<>();
        }
        return postorderTraversal(root,new ArrayList<>());
    }

    public List<Integer> postorderTraversal(TreeNode root,List<Integer> tmp){
        if (root == null){
            return null;
        }
        postorderTraversal(root.left,tmp);
        postorderTraversal(root.right,tmp);
        tmp.add(root.val);
        return tmp;
    }


    /**
     * 非递归
     * @param root
     * @return
     */
    public List<Integer> postorderTraversal2(TreeNode root) {
        if (root == null){
            return new ArrayList<>();
        }
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (root.right == null || root.right == prev){
                result.add(root.val);
                prev = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return result;
    }
}
